package com.example.aiservice.controller;

import com.example.aiservice.entity.AiModel;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/ai")
public class AiController {

    private final RestTemplate restTemplate = new RestTemplate();

    @GetMapping("/model")
    public AiModel getAiModel() {
        AiModel model = new AiModel();
        model.setId(1L);
        model.setName("GPT-4");
        model.setDescription("Advanced AI model by OpenAI");
        return model;
    }

    @GetMapping("/response")
    public String getResponse() {
        return "This is a response from the AI service.";
    }

    @GetMapping("/ask")
    public String askAi(@RequestParam String question) {
        // 简单模拟AI回答
        if (question.toLowerCase().contains("hello")) {
            return "Hello! How can I assist you today?";
        } else if (question.toLowerCase().contains("weather")) {
            return "The weather is sunny and warm.";
        } else {
            return "I'm sorry, I don't have an answer for that.";
        }
    }

    @GetMapping("/deepseek")
    public String deepSeek(@RequestParam String query) {
        // DeepSeek API endpoint
        String apiUrl = "https://api.deepseek.com/v1/query"; // 确保URL正确

        // Headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer YOUR_DEEPSEEK_API_KEY"); // 确保API Key正确

        // Request body
        String requestBody = "{\"query\": \"" + query + "\"}"; // 确保请求体符合API要求

        // Create the HTTP entity
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        try {
            // Send the POST request
            ResponseEntity<String> response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, String.class);

            // Return the response body
            return response.getBody();
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                return "Error: The requested resource was not found. Please check the API URL and configuration.";
            } else {
                return "Error: " + e.getMessage();
            }
        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }
}